//
//  ServerTCPManager.m
//  LazyHome
//
//  Created by yh on 2018/5/8.
//  Copyright © 2018年 yh. All rights reserved.
//

#import "ServerTCPManager.h"
#import "NSMutableData+BufferHandler.h"
#import <MJExtension/MJExtension.h>
#import "LHCmd.h"

@implementation ServerTCPManager
+ (instancetype)shareManager{
    static dispatch_once_t onceToken;
    static ServerTCPManager *shareInstance = nil;
    dispatch_once(&onceToken, ^{
        shareInstance = [[ServerTCPManager alloc]init];
    });
    return shareInstance;
}


- (TCPClient *)creatClientWithHost:(NSString *)host port:(NSString *)port localport:(NSString *)localport error:(NSError *__autoreleasing *)errPtr{
    TCPClient *client = [TCPClient clientWithHost:host port:port localport:localport error:errPtr];
    client.delegate = self;
    
    [self.clients addObject:client];
    self.client = client;
    return client;
}

- (void)sendMessage:(LHMessage *)msg toClient:(TCPClient *)clinet success:(void(^)(LHMessage *message))success failure:(void(^)(void))failure{
    NSLog(@"msg to server : %@",[msg.data mj_JSONObject]);
    [clinet sendData:[msg messageData] withTimeout:-1 tag:-1];
}


- (BOOL)tcpClient:(TCPClient *)tcpClient shouldReconnectForNetChange:(AFNetworkReachabilityStatus)networkReachabilityStatus{
    return YES;
}

- (void)tcpClient:(TCPClient *)tcpClient socket:(GCDAsyncSocket *)sock didWriteData:(NSData *)data withTag:(long)tag{
    
    
}

- (void)tcpClient:(TCPClient *)tcpClient socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
    LHMessage *msg = [[LHMessage alloc]init];
    while (tcpClient.reciveBuffer.handle_index.integerValue < tcpClient.reciveBuffer.length) {
        NSData *dat = [tcpClient.reciveBuffer readDataWithLength:1];
        if ([dat toUChar] == 0xaa) {
            msg.headData = dat;
            break;
        }
    }
    if (tcpClient.reciveBuffer.handle_index.integerValue + 1 < tcpClient.reciveBuffer.length) {
        msg.fnData = [tcpClient.reciveBuffer readDataWithLength:1];
    }else{
        [tcpClient.reciveBuffer resetHandleIndex2Zero];;
    }
    
    if (tcpClient.reciveBuffer.handle_index.integerValue + 2 < tcpClient.reciveBuffer.length) {
        msg.cmdData = [tcpClient.reciveBuffer readDataWithLength:2];
    }else{
        [tcpClient.reciveBuffer resetHandleIndex2Zero];;
    }
    
    if (tcpClient.reciveBuffer.handle_index.integerValue + 2 < tcpClient.reciveBuffer.length) {
        msg.lengthData = [tcpClient.reciveBuffer readDataWithLength:2];
    }else{
        [tcpClient.reciveBuffer resetHandleIndex2Zero];;
    }
    
    if (tcpClient.reciveBuffer.handle_index.integerValue + [msg.lengthData toUShort] <= tcpClient.reciveBuffer.length) {
        msg.data = [tcpClient.reciveBuffer readDataWithLength: [msg.lengthData toUShort]];
        //解析完一帧了
        NSLog(@"data from server : %@",[msg.data mj_JSONObject]);
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_TCP_MESSAGE_CAME object:msg];
    }else{
        [tcpClient.reciveBuffer resetHandleIndex2Zero];;
    }
    
}

- (void)tcpClient:(TCPClient *)tcpClient writeChannelFreeInTimer:(NSTimer *)timer{
    NSLog(@"heart beat 💕");
    NSDictionary *heartBeatInfo = @{
                                    @"time":@"ssssss",
                                    };
    LHMessage *heartBeatMessage = [LHMessage messageWithData:[heartBeatInfo mj_JSONData] cmd:CMD_P2S_HEARTBEAT];
    [self sendMessage:heartBeatMessage toClient:tcpClient success:^(LHMessage *message) {
        
    } failure:^{
        
    }];
    
}

- (void)tcpClient:(TCPClient *)tcpClient readChannelFreeInTimer:(NSTimer *)timer{
    NSLog(@"长时间收不到服务器的回应");
    //判断已经和服务器断开
    [tcpClient resetConnect];
}

- (void)tcpClient:(TCPClient *)tcpClient connectStatusChange:(TCPClientStatus)status{
    [[NSNotificationCenter defaultCenter] postNotificationName:SERVER_CONNECT_STATUS_CHANGE object:nil];
    if (status == TCPClientStatusDisConnect) {
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前连接已经断开" preferredStyle:UIAlertControllerStyleAlert];
//        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            
//        }]];
//        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:^{
//            
//        }];
    }
    
    
}

@end
